package com.coze.lg.cozeagent.controller;

import com.coze.openapi.service.service.CozeAPI;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.text.DecimalFormat;

public class SessionMySocket extends SessionParent {
    private final MySocket mySocket;
    public SessionMySocket(AipSpeech aipSpeech, CozeAPI cozeAPI, Socket socket) {
        super(aipSpeech, cozeAPI);
        this.mySocket = new MySocket(socket);
    }
    @Override
    public void do_restart() {
        try {
            System.out.println("do_restart: start read");
            do_start(mySocket.read());
        }
        catch (IOException e) {
            System.out.println("do_restart: " + e.getMessage());
        }
    }
    @Override
    public void sessionParentWriteFunc(byte[] data) throws IOException {
        mySocket.write(data);
        System.out.printf("sessionParentWriteFunc: %s\n", mySocket.socket.getRemoteSocketAddress());
    }
    class MySocket {
        public final Socket socket;
        public MySocket(Socket socket) {
            this.socket = socket;
        }
        public byte[] read() throws IOException {
            InputStream in = socket.getInputStream();
            System.out.println("MySocket.read start: " + socket.getRemoteSocketAddress());
            byte[] beginFormat = in.readNBytes(10);
            String beginFormatString = new String(beginFormat);
            System.out.println("MySocket.read beginFormatString: " + beginFormatString);
            int length = 0;
            if (beginFormatString.charAt(0) == '-' && beginFormatString.charAt(9) == '-' ) {
                String lengthStr = beginFormatString.substring(1, 9);
                length = Integer.parseInt(lengthStr);
            }
            else {
                throw new IOException("前缀码不正确");
            }
            System.out.println("MySocket.read length: " + length);
            return in.readNBytes(length);
        }
        public void write(byte[] data) throws IOException {
            OutputStream out = socket.getOutputStream();
            int length = data.length;
            // 先生成固定长度的数字字符串（不足补零）
            DecimalFormat df = new DecimalFormat("0".repeat(8));
            String digits = df.format(length);
            String beginFormatString = "-" + digits + "-";
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byteArrayOutputStream.write(beginFormatString.getBytes());
            byteArrayOutputStream.write(data);
            out.write(byteArrayOutputStream.toByteArray());
            out.flush();
        }
    }
}
